import { createApp } from 'vue'
import Message from '@renderer/components/Message.vue'

/** 
   @description 扁平化数组
  * @param {Array}  array 要扁平化的数组
  * @return {string || function} 生成对象中key的函数
*/
export const flatArray = (array, generateKey) => {
  if (!Array.isArray(array)) return
  if (typeof generateKey === 'string') {
    const key = generateKey
    generateKey = (item) => item[key]
  }
  const target = {}
  array.forEach((item, index) => {
    const key = generateKey(item, index, array)
    if (target[key]) {
      return target[key].push(item)
    }
    target[key] = [item]
  })
  return target
}

/**
 * 根据日期字段排序
 * @param arr 包含日期字段的数组
 */
export const sortByDate = (arr: Array<any>) => {
  arr.sort((a, b) => {
    return -a.createDate.localeCompare(b.createDate)
  })
}

export const getDateString = (dateStr: string) => {
  const date = new Date(dateStr)
  if (date) {
    // 获取月份、日期和星期几
    const month = date.getMonth() + 1 // 月份从 0 开始，需要 +1
    const day = date.getDate()
    const weekdays = ['日', '一', '二', '三', '四', '五', '六']
    const weekday = weekdays[date.getDay()] // 获取星期几
    // 拼接成目标格式
    const formattedDate = `${month}月${day}日, 周${weekday}`
    return formattedDate
  } else {
    return ''
  }
}

interface MessageOptions {
  type: 'sucess' | 'error' | 'info' | 'warning'
  content: string
  duration?: number
  title?: string
}

/**
 * 消息提示函数
 * @param options 消息参数
 */
export const message = (options: MessageOptions) => {
  let messageList = document.getElementById('message-list')
  if (!messageList) {
    messageList = document.createElement('div')
    messageList.id = 'message-list'
    document.body.appendChild(messageList)
  }
  const div = document.createElement('div')
  div.className = 'xz-message'
  div.id = `message-${Date.now()}`
  document.body.appendChild(div)
  const msg = createApp(Message, {
    duration: options.duration || 2000,
    type: options.type,
    message: options.content
  })
  msg.mount(div)
  messageList.appendChild(div)
  setTimeout(() => {
    messageList.removeChild(div)
    msg.unmount()
  }, options.duration || 2000)
}

/**
 *
 * @param filePath 文件相对路径
 * @returns 完整路径
 */
export const getAssetsFile = (filePath: string) => {
  return new URL(`../assets/${filePath}`, import.meta.url).href
}

interface IconMap {
  [key: string]: {
    name: string
    icons: string[]
  }
}

/**
 *
 * @returns 获取所有的图标
 */
export const getIcons = (): IconMap => {
  const yuexiaoIcons = import.meta.glob('../assets/icon/yuexiao/*.webp', { eager: true })
  const kanteleliaIcons = import.meta.glob('../assets/icon/kanteleila/*.webp', { eager: true })
  return {
    yuexiao: {
      name: '月宵',
      icons: Object.values(yuexiaoIcons).map((module: any) => module.default)
    },
    kanteleila: {
      name: '坎特雷拉',
      icons: Object.values(kanteleliaIcons).map((module: any) => module.default)
    }
  }
}
